package com.tianji.learning.service.impl;

import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BooleanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.vo.SignResultVO;
import com.tianji.learning.mq.message.PointsMessage;
import com.tianji.learning.service.ISignRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SignRecordServiceImpl implements ISignRecordService {

    private final StringRedisTemplate redisTemplate;

    private final RabbitMqHelper mqHelper;

    /**
     * 签到
     *
     * @return
     */
    @Override
    public SignResultVO addSignRecords() {
        //1.签到 ，操作bitmap
        //1.1获得用户id
        Long userId = UserContext.getUser();
        //1.2获得当前日期
        LocalDate now = LocalDate.now();
        //1.3拼接key sign:uid:110:202301
        String key = RedisConstants.SIGN_RECORD_KEY_PREFIX + userId + ":" + now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        //1.4 计算offset
        int offset = now.getDayOfMonth() - 1;
        //1.5保存
        Boolean result = redisTemplate.opsForValue().setBit(key, offset, true);
        if (BooleanUtils.isTrue(result)) {
            throw new BizIllegalException("不能重复签到");
        }
        //2.统计连续的签到天数
        int signDays = countSignDays(key, now.getDayOfMonth());
        //3.积分功能
        int rewardPoints = 0;
        switch (signDays) {
            case 7:
                rewardPoints = 10;
                break;
            case 14:
                rewardPoints = 20;
                break;
            case 28:
                rewardPoints = 40;
                break;
        }
        //4
        mqHelper.send(MqConstants.Exchange.LEARNING_EXCHANGE,
                MqConstants.Key.SIGN_IN,
                PointsMessage.of(userId, rewardPoints + 1));
        //封装vo
        SignResultVO vo = new SignResultVO();
        vo.setRewardPoints(rewardPoints);
        vo.setSignDays(signDays);
        return vo;
    }


    /**
     * 查询签到记录
     *
     * @return
     */
    @Override
    public Byte[] querySignRecords() {
        //1.获得当前用户
        Long userId = UserContext.getUser();
        //2.获得当前日期
        LocalDate now = LocalDate.now();
        int dayOfMonth = now.getDayOfMonth();
        //3.拼接key
        String key = RedisConstants.SIGN_RECORD_KEY_PREFIX + userId + ":" + now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        //4.执行bitfield 获得截至到今天的签到情况 BITFIELD key GET u[dayOfMonth] 0
        List<Long> result = redisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (CollUtils.isEmpty(result)) {
            return new Byte[0];
        }
        Byte[] bytes = new Byte[dayOfMonth];
        int num = result.get(0).intValue();
        //数组下标
        int pos = dayOfMonth - 1; //从尾巴填充往前去填充
        while (pos >= 0) {
            bytes[pos] = (byte) (num & 1);
            num >>>= 1;
            pos--;
        }
        return bytes;
    }

    private int countSignDays(String key, int dayOfMonth) {
        //1.执行bitfield 获得截至到今天的签到情况 BITFIELD key GET u[dayOfMonth] 0
        List<Long> list = redisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (CollUtils.isEmpty(list)) {
            return 0;
        }
        //2.取出结果
        int num = list.get(0).intValue();
        int count = 0;
        while ((num & 1) == 1) {
            count++;
            num = num >>> 1;
        }
        return count;
    }
}